package com.czk.utils;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/4/22 11:11
 */
public class SerializationUtil {
    private static Map<Class<?>, Schema<?>> map = new ConcurrentHashMap<>();
    private static Objenesis objenesis = new ObjenesisStd();

    public SerializationUtil() {
    }

    /**
     * 对象序列化
     *
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> byte[] serializer(T obj) {
        Class<T> clazz = (Class<T>) obj.getClass();
        //
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        //
        try {
            Schema<T> schema =  getSchema(clazz);
            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 字节数组转换为对象
     *
     * @param data
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> T deserialize(byte[] data, Class<T> cls) {
        T t = objenesis.newInstance(cls);
        // 拿到约束
        Schema<T> schema = getSchema(cls);
        ProtostuffIOUtil.mergeFrom(data, t, schema);
        return t;
    }

    /**
     * 创建schema转换为字节存储在集合中
     *
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> Schema<T> getSchema(Class<T> cls) {
        Schema<T> schema = (Schema<T>) map.get(cls);
        if (schema == null) {
            schema = RuntimeSchema.createFrom(cls);
            map.put(cls, schema);
        }
        return schema;
    }
}
